﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using FileSquirrel.Logic;
using FileSquirrel.Logic.XSD;
using FileSquirrel.Properties;

namespace FileSquirrel
{
    public partial class FileSquirrel : Form
    {
        #region Properties & Variables

        private Logic.XSD.UserSettings _userSettings;
        private readonly char[] _alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".ToCharArray();
        private bool _isCopy = false;
        private int _totalCopySize;
        private Copier copier;
        private FolderBrowserDialog copyToDialog;

        private BackgroundWorker bgw_Copy = new BackgroundWorker();
        private BackgroundWorker bw_LibraryUpdate = new BackgroundWorker();

        private Indexer indexer;

        public Indexer _Indexer
        {
            get { return indexer ?? (indexer = new Indexer(Settings.Default.LibraryName, Settings.Default.LibraryDir)); }
        }

        #endregion Properties & Variables

        #region Constructors

        public FileSquirrel()
        {
            InitializeComponent();
            Reader._libName = Settings.Default.LibraryName;
            Reader._libdir = Settings.Default.LibraryDir;

            ConnectEventHandlers();
        }

        public FileSquirrel(string cmdFile)
        {
            InitializeComponent();

            Reader._libName = Settings.Default.LibraryName;
            Reader._libdir = Settings.Default.LibraryDir;

            ConnectEventHandlers();

            if (string.Compare(new FileInfo(cmdFile).Extension, ".fsr", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                copyToDialog = new FolderBrowserDialog();
                copyToDialog.ShowDialog();

                if (!string.IsNullOrEmpty(copyToDialog.SelectedPath))
                {
                    _isCopy = true;
                    copier = new Copier(cmdFile, Settings.Default.LibraryName, Settings.Default.LibraryDir);

                    _totalCopySize = (from dr in Reader.GlobalRequestLibrary.RequestList.AsEnumerable()
                                      select dr.Size).Sum();
                    string tmpSize;
                    tmpSize = _totalCopySize > 1024
                                  ? string.Format("{0:f} GB", (decimal)_totalCopySize / 1024)
                                  : string.Format("{0:f} MB", _totalCopySize);

                    tsStatus.Text = string.Format("Copying - {0}", tmpSize);
                }
            }
            else
            {
                //TODO open any library file from file associations
                //OpenLibraryFromFile(cmdFile);
            }
        }

        private void ConnectEventHandlers()
        {
            bw_LibraryUpdate.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw_LibraryUpdate.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bgw_Copy.DoWork += new DoWorkEventHandler(bgw_Copy_DoWork);
            bgw_Copy.ProgressChanged += new ProgressChangedEventHandler(bgw_Copy_ProgressChanged);
            bgw_Copy.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_Copy_RunWorkerCompleted);
        }

        #endregion Constructors

        #region Methods

        private void Initialize()
        {
            ToggleLibraryRefreshRebuild();

            tsStatus.Text = "Updating Library.";
            LoadConfig();

            tsProgressBar.Value = 0;
            tsProgressBar.Visible = true;
            tsProgressBar.Style = ProgressBarStyle.Marquee;

            bw_LibraryUpdate.RunWorkerAsync();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            _Indexer.GatherFiles(_userSettings.Category);
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tsProgressBar.Visible = false;
            DialogResult dr = MessageBox.Show("Library Update done. Reload?", "Update Done", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (dr == DialogResult.Yes)
            {
                LibraryDataSet.FilesDataTable dtFiles = Reader.GlobalLibrary._Files;

                PopulateTree(dtFiles);
                LoadLibrary(dtFiles);
                this.Text = string.Format("FileSquirrel - {0}", Settings.Default.LibraryName);
            }
            ToggleLibraryRefreshRebuild();

            tsStatus.Text = "Library updated.";
        }

        private void LoadConfig()
        {
            _userSettings = Reader.UserSettings;
        }

        private void ToggleLibraryRefreshRebuild()
        {
            refreshToolStripMenuItem.Enabled = !refreshToolStripMenuItem.Enabled;
            rebuildAllToolStripMenuItem.Enabled = !rebuildAllToolStripMenuItem.Enabled;
        }

        private void LoadLibrary(LibraryDataSet.FilesDataTable dtFiles)
        {
            FS_Files_DGV.DataSource = dtFiles;
            FS_Files_DGV.Sort(FS_Files_DGV.Columns["FileName"], ListSortDirection.Ascending);
            fs_statusItemCount.Text = string.Format("Item Count : {0}", dtFiles.Rows.Count);

            //PopulateRequestChecks(dtFiles);

            int iSize = (from dr in dtFiles.AsEnumerable()
                         select dr.Size).Sum();
            string tmpSize;
            tmpSize = iSize > 1024 ? string.Format("{0:f} GB", (decimal)iSize / 1024) : string.Format("{0:f} MB", iSize);

            fs_statusItemSize.Text = string.Format("Total Size : {0}", tmpSize);
        }

        private void PopulateTree(LibraryDataSet.FilesDataTable dtFiles)
        {
            FS_treeView.Nodes.Clear();
            TreeNode tnLib = FS_treeView.Nodes.Add("Library");

            foreach (DataRow category in dtFiles.DefaultView.ToTable(true, "Category").Rows)
            {
                TreeNode tnCat = new TreeNode(category.ItemArray[0].ToString());

                if (tnCat.Text.ToUpper() != "SERIES")
                {
                    foreach (char letter in _alphabet)
                    {
                        string let = letter.ToString(CultureInfo.InvariantCulture);

                        tnCat.Nodes.Add(let, let);
                    }
                }

                foreach (LibraryDataSet.FilesRow file in dtFiles.Select(string.Format("Category = '{0}'", tnCat.Text)))
                {
                    if (tnCat.Text.ToUpper() == "SERIES" && !file.IsShowNull())
                    {
                        int showInd = tnCat.Nodes.IndexOfKey(file.Show);

                        if (showInd == -1)
                        {
                            showInd = tnCat.Nodes.Add(file.Show, file.Show).Index;
                        }

                        int seasonInd = tnCat.Nodes[showInd].Nodes.IndexOfKey(file.Season);

                        if (seasonInd == -1)
                        {
                            seasonInd = tnCat.Nodes[showInd].Nodes.Add(file.Season, file.Season).Index;
                        }

                        //  Add files to tree as lowest level
                        //tnCat.Nodes[showInd].Nodes[seasonInd].Nodes.Add(file.Path, file.Name);
                    }
                    //else
                    //{
                    //    int alphaInd = tnCat.Nodes.IndexOfKey(file.Name.Substring(0, 1));

                    //    if (alphaInd == -1)
                    //        alphaInd = tnCat.Nodes.IndexOfKey("#");

                    //    //  Add files to tree as lowest level
                    //    tnCat.Nodes[alphaInd].Nodes.Add(file.Path, file.Name);
                    //}
                }

                tnLib.Nodes.Add(tnCat);
            }

            FS_treeView.Sort();
        }

        private void PopulateRequestChecks(LibraryDataSet.FilesDataTable dtFiles)
        {
            EnumerableRowCollection<string> rqsub = null;
            using (LibraryDataSet.RequestListDataTable rqlib = FS_Request_DGV.DataSource as LibraryDataSet.RequestListDataTable)
            {
                if (rqlib != null)
                    rqsub = from o in rqlib select o.Path;
            }
            if (rqsub != null)
            {
                foreach (var rqpath in rqsub)
                {
                    ///TODO Find way of getting sorted datagridview's row with index from datatable
                }
            }
        }

        private void ToggleVideoColumns(string Category)
        {
            if (Category.ToUpper() == "SERIES" || Category.ToUpper() == "MOVIES")
            {
                FS_Files_DGV.Columns["Duration"].Visible = true;
                FS_Files_DGV.Columns["Resolution"].Visible = true;
            }
            else
            {
                FS_Files_DGV.Columns["Duration"].Visible = false;
                FS_Files_DGV.Columns["Resolution"].Visible = false;
            }
        }

        #endregion Methods

        #region Event Handlers

        private void bgw_Copy_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            tsProgressBar.Maximum = e.ProgressPercentage;
            tsProgressBar.Value++;

            int iSize = (from dr in Reader.GlobalRequestLibrary.RequestList.AsEnumerable()
                         select dr.Size).Sum();

            iSize = _totalCopySize - iSize;
            string tmpsize = iSize > 1024 ? string.Format("{0:f} GB", (decimal)iSize / 1024) : string.Format("{0:f} MB", iSize);
            string tmpTotalsize = _totalCopySize > 1024 ? string.Format("{0:f} GB", (decimal)_totalCopySize / 1024) : string.Format("{0:f} MB", _totalCopySize);

            tsStatus.Text = string.Format("Copied - {0}/{1}", tmpsize, tmpTotalsize);
        }

        private void bgw_Copy_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tsStatus.Text = "Copy done!";
            tsProgressBar.Visible = false;
        }

        private void bgw_Copy_DoWork(object sender, DoWorkEventArgs e)
        {
            copier.Copy(copyToDialog.SelectedPath, bgw_Copy);
        }

        private void FileSquirrel_Load(object sender, EventArgs e)
        {
            AddCheckBoxDataColumn();

            FS_splitContainer2.Panel2Collapsed = true;
            FS_Files_DGV.AutoGenerateColumns = false;
            FS_Request_DGV.AutoGenerateColumns = false;
            FS_Ignore_DGV.AutoGenerateColumns = false;

            if (FirstRun() && !_isCopy)
            {
                UserSettings userSettings = new UserSettings(FirstRun());
                userSettings.ShowDialog();
            }

            LibraryDataSet.FilesDataTable dtFiles = Reader.GlobalLibrary._Files;

            if (_isCopy)
            {
                bgw_Copy.WorkerReportsProgress = true;

                bgw_Copy.RunWorkerAsync(null);

                tsProgressBar.Value = 0;
                tsProgressBar.Visible = true;
            }

            if (dtFiles.Count > 0)
            {
                PopulateTree(dtFiles);
                LoadLibrary(dtFiles);
            }
            else
            {
                DialogResult dr = MessageBox.Show("Library is empty. Create new? This will take some time to complete", "Library Empty", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dr == DialogResult.Yes)
                {
                    Initialize();
                }
            }

            Text = "FileSquirrel - " + Settings.Default.LibraryName;
            _Indexer.RequestFilesName = string.Format("{0}_RequestFrom_{0}", Settings.Default.LibraryName);
        }

        private bool FirstRun()
        {
            return string.IsNullOrEmpty(Settings.Default.LibraryName) ||
                   string.IsNullOrEmpty(Settings.Default.LibraryDir);
        }

        private void AddCheckBoxDataColumn()
        {
            // customize dataviewgrid, add checkbox column
            DataGridViewCheckBoxColumn checkboxColumn = new DataGridViewCheckBoxColumn
            {
                Width = 30,
                Frozen = true,
                DefaultCellStyle =
                {
                    Alignment =
                        DataGridViewContentAlignment.MiddleCenter
                }
            };

            FS_Files_DGV.Columns.Insert(0, checkboxColumn);

            // add checkbox header
            Rectangle rect = FS_Files_DGV.GetCellDisplayRectangle(0, -1, true);
            // set checkbox header to center of header cell. +1 pixel to position correctly.
            rect.X = rect.Location.X + (rect.Width / 4) + 1;
            rect.Y = rect.Location.Y + (rect.Height / 8) + 2;

            CheckBox checkboxHeader = new CheckBox { Name = "checkboxHeader", Size = new Size(14, 14), Location = rect.Location };
            checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged);

            FS_Files_DGV.Controls.Add(checkboxHeader);
        }

        private void checkboxHeader_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < FS_Files_DGV.RowCount; i++)
            {
                FS_Files_DGV[0, i].Value = ((CheckBox)FS_Files_DGV.Controls.Find("checkboxHeader", true)[0]).Checked;

                FS_Files_DGV.EndEdit();
            }
        }

        #region ToolStripMenu

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Initialize();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserSettings userSettings = new UserSettings(FirstRun());
            userSettings.ShowDialog();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutWindow aboutWindow = new AboutWindow();
            aboutWindow.Show(this);
        }

        #endregion ToolStripMenu

        #region ToolStripButtons

        private void Request_Ignore_TogleButton_Click(object sender, EventArgs e)
        {
            FS_splitContainer2.Panel2Collapsed = !FS_splitContainer2.Panel2Collapsed;
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog opd = new OpenFileDialog();
            opd.Filter = "FileSquirrel (*.fsl) | *.fsl";
            opd.Title = "FileSquirrel - Select Library File to open and compare against.";
            if (opd.ShowDialog() == DialogResult.OK)
            {
                OpenLibraryFromFile(opd.FileName);
            }
        }

        private void OpenLibraryFromFile(string filename)
        {
            Reader.ResetToOwnLibrary();
            LibraryDataSet.FilesDataTable dinstinctFiles =
                Reader.GetDistinctFilesDataSet(Reader.GlobalLibrary._Files, filename);
            PopulateTree(dinstinctFiles);
            LoadLibrary(dinstinctFiles);

            _Indexer.RequestFilesName = Path.GetFileNameWithoutExtension(new FileInfo(filename).Name);
            this.Text = string.Format("FileSquirrel - {0}", _Indexer.RequestFilesName);
            _Indexer.RequestFilesName = string.Format("{0}_RequestFrom_{1}",
                                                      Path.GetFileNameWithoutExtension(new FileInfo(filename).Name),
                                                      Settings.Default.LibraryName);
        }

        #endregion ToolStripButtons

        #region Context Menu

        //Add files to request list
        private void fs_AddtoRequest_Click(object sender, EventArgs e)
        {
            LibraryDataSet.FilesDataTable dtFiles = (LibraryDataSet.FilesDataTable)FS_Files_DGV.DataSource;
            if (Reader.GlobalRequestLibrary == null)
            {
                Reader.GlobalRequestLibrary = new LibraryDataSet();
                string requestLib = ((LibraryDataSet.LibraryRow)Reader.GlobalLibrary.Library.Rows[0]).Library_Id;
                Reader.GlobalRequestLibrary.Library.AddLibraryRow(requestLib);
            }

            DataGridViewRow dgvRequestRow = FS_Files_DGV.Rows[FS_Files_DGV.Rows.GetFirstRow(DataGridViewElementStates.Selected)];

            LibraryDataSet.FilesRow requestRow = dtFiles.FindByPath(dgvRequestRow.Cells["FilePath"].Value.ToString());

            Reader.GlobalRequestLibrary.RequestList.AddRequestListRow((LibraryDataSet.LibraryRow)Reader.GlobalRequestLibrary.Library.Rows[0], requestRow.Path, requestRow.Name, requestRow.Category, requestRow.Size);

            dtFiles.RemoveFilesRow(requestRow);
            FS_Files_DGV.Refresh();

            FS_Request_DGV.DataSource = Reader.GlobalRequestLibrary.RequestList;
            FS_Request_DGV.Refresh();
            FS_Ignore_Request_tabControl.SelectedTab = Request_tabPage;
            FS_splitContainer2.Panel2Collapsed = false;
            _Indexer.SaveRequest();
        }

        //Adds files to ignore list
        private void fs_AddtoIgnore_Click(object sender, EventArgs e)
        {
            LibraryDataSet.FilesDataTable dtFiles = (LibraryDataSet.FilesDataTable)FS_Files_DGV.DataSource;

            DataGridViewRow dgvIgnoreRow = FS_Files_DGV.Rows[FS_Files_DGV.Rows.GetFirstRow(DataGridViewElementStates.Selected)];

            LibraryDataSet.FilesRow ignoreRow = dtFiles.FindByPath(dgvIgnoreRow.Cells["FilePath"].Value.ToString());

            Reader.GlobalLibrary.IgnoreList.AddIgnoreListRow((LibraryDataSet.LibraryRow)Reader.GlobalLibrary.Library.Rows[0], ignoreRow.Path, ignoreRow.Name);

            dtFiles.RemoveFilesRow(ignoreRow);
            FS_Files_DGV.Refresh();

            FS_Ignore_DGV.DataSource = Reader.GlobalLibrary.IgnoreList;
            FS_Ignore_DGV.Refresh();
            FS_Ignore_Request_tabControl.SelectedTab = Ignore_tabPage;
            FS_splitContainer2.Panel2Collapsed = false;
        }

        //Opens file location and select item
        private void openFileLocationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvItem = FS_Files_DGV.Rows[FS_Files_DGV.Rows.GetFirstRow(DataGridViewElementStates.Selected)];
            FileInfo fi = new FileInfo(dgvItem.Cells["FilePath"].Value.ToString());
            if (fi.Exists)
            {
                Process.Start("explorer.exe", string.Format("/select,{0}", fi.FullName));
            }
        }

        #endregion Context Menu

        private void FS_dataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hitTestInfo;
            if (e.Button == MouseButtons.Right)
            {
                hitTestInfo = FS_Files_DGV.HitTest(e.X, e.Y);
                if (hitTestInfo.RowIndex >= 0)
                {
                    FS_Files_DGV.ClearSelection();
                    FS_Files_DGV.Rows[hitTestInfo.RowIndex].Selected = true;
                }
                openFileLocationToolStripMenuItem.Enabled = CheckifFileExists();
            }
        }

        private bool CheckifFileExists()
        {
            var CErow = ((LibraryDataSet.FilesRow)((DataRowView)(FS_Files_DGV.SelectedRows[0].DataBoundItem)).Row);
            FileInfo fi = new FileInfo(CErow.Path);
            return fi.Exists;
        }

        private void FS_treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            LibraryDataSet.FilesDataTable dtFiles = Reader.GlobalLibrary._Files;

            if (e.Node.Level == 0)  // Library
            {
                LoadLibrary(dtFiles);
                FS_Files_DGV.Columns["Category"].Visible = true;
            }
            else
            {
                if (e.Node.Level == 1)  // Category
                {
                    LibraryDataSet.FilesDataTable dtCategory = new LibraryDataSet.FilesDataTable();

                    foreach (DataRow row in dtFiles.Select(string.Format("Category = '{0}'", e.Node.Text.Replace(@"'", "''"))))
                    {
                        dtCategory.ImportRow(row);
                    }

                    LoadLibrary(dtCategory);
                    ToggleVideoColumns(e.Node.Text);
                }
                else if (e.Node.Level == 2)
                {
                    if (e.Node.Parent.Text.ToUpper() == "SERIES")  // Show
                    {
                        LibraryDataSet.FilesDataTable dtShow = new LibraryDataSet.FilesDataTable();

                        foreach (DataRow row in dtFiles.Select(string.Format("Category = '{0}' AND Show = '{1}'", e.Node.Parent.Text, e.Node.Text.Replace(@"'", "''"))))
                        {
                            dtShow.ImportRow(row);
                        }

                        LoadLibrary(dtShow);
                    }
                    else  // Alphabet
                    {
                        LibraryDataSet.FilesDataTable dtAlphabet = new LibraryDataSet.FilesDataTable();

                        if (e.Node.Text == "#")  // Non alphabet characters
                        {
                            string query = "(";

                            foreach (char letter in _alphabet)
                            {
                                if (letter != '#')
                                    query += "'" + letter + "',";
                            }

                            query = query.Substring(0, query.Length - 1) + ")";

                            foreach (DataRow row in dtFiles.Select(string.Format("Category = '{0}' AND Substring(Name, 1, 1) NOT IN {1}", e.Node.Parent.Text.Replace(@"'", "''"), query)))
                            {
                                dtAlphabet.ImportRow(row);
                            }
                        }
                        else  // A to Z
                        {
                            foreach (DataRow row in dtFiles.Select(string.Format("Category = '{0}' AND Name LIKE '{1}%'", e.Node.Parent.Text, e.Node.Text.Replace(@"'", "''"))))
                            {
                                dtAlphabet.ImportRow(row);
                            }
                        }

                        LoadLibrary(dtAlphabet);
                    }
                    ToggleVideoColumns(e.Node.Parent.Text);
                }
                else if (e.Node.Level == 3)  // Season
                {
                    if (e.Node.Parent.Parent.Text.ToUpper() == "SERIES")
                    {
                        LibraryDataSet.FilesDataTable dtSeason = new LibraryDataSet.FilesDataTable();

                        foreach (DataRow row in dtFiles.Select(string.Format("Category = '{0}' AND Show = '{1}' AND Season = '{2}'", e.Node.Parent.Parent.Text.Replace(@"'", "''"), e.Node.Parent.Text.Replace(@"'", "''"), e.Node.Text.Replace(@"'", "''"))))
                        {
                            dtSeason.ImportRow(row);
                        }

                        LoadLibrary(dtSeason);
                    }
                    ToggleVideoColumns(e.Node.Parent.Parent.Text);
                }
                FS_Files_DGV.Columns["Category"].Visible = false;
            }
        }

        private void FS_Files_DGV_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                int iTrueCount = FS_Files_DGV.SelectedRows.Cast<DataGridViewRow>().Count(x => Convert.ToBoolean(x.Cells[0].Value));

                foreach (DataGridViewRow row in ((DataGridView)sender).SelectedRows)
                {
                    row.Cells[0].Value = (iTrueCount < FS_Files_DGV.SelectedRows.Count);
                }
            }
        }

        private void tsBtnRequest_Click(object sender, EventArgs e)
        {
            var chkdRows = FS_Files_DGV.Rows.Cast<DataGridViewRow>().Where(x => Convert.ToBoolean(x.Cells[0].Value));

            if (Reader.GlobalRequestLibrary == null)
            {
                Reader.GlobalRequestLibrary = new LibraryDataSet();
                string requestLib = ((LibraryDataSet.LibraryRow)Reader.GlobalLibrary.Library.Rows[0]).Library_Id;
                Reader.GlobalRequestLibrary.Library.AddLibraryRow(requestLib);
            }

            foreach (var chkdRow in chkdRows)
            {
                var crow = ((LibraryDataSet.FilesRow)((DataRowView)(chkdRow.DataBoundItem)).Row);
                var _rowexists = Reader.GlobalRequestLibrary.RequestList.FindByPath(crow.Path);

                if (_rowexists == null)
                {
                    Reader.GlobalRequestLibrary.RequestList.AddRequestListRow((LibraryDataSet.LibraryRow)Reader.GlobalRequestLibrary.Library.Rows[0], crow.Path, crow.Name, crow.Category, crow.Size);
                }
            }
            FS_Ignore_Request_tabControl.SelectedTab = Request_tabPage;
            FS_splitContainer2.Panel2Collapsed = false;
            _Indexer.SaveRequest();
            FS_Request_DGV.DataSource = Reader.GlobalRequestLibrary.RequestList;
            FS_Request_DGV.Refresh();
        }

        private void FS_Request_DGV_MouseDown(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hitTestInfo;
            if (e.Button == MouseButtons.Right)
            {
                hitTestInfo = FS_Files_DGV.HitTest(e.X, e.Y);
                if (hitTestInfo.RowIndex >= 0)
                {
                    FS_Request_DGV.ClearSelection();
                    FS_Request_DGV.Rows[hitTestInfo.RowIndex].Selected = true;
                }
            }
        }

        private void fs_rightClickRequst_Click(object sender, EventArgs e)
        {
            LibraryDataSet.RequestListDataTable dtRFiles = (LibraryDataSet.RequestListDataTable)FS_Request_DGV.DataSource;

            DataGridViewRow dgvRequestRow = FS_Files_DGV.Rows[FS_Files_DGV.Rows.GetFirstRow(DataGridViewElementStates.Selected)];

            LibraryDataSet.RequestListRow removeRequest = dtRFiles.FindByPath(dgvRequestRow.Cells["FilePath"].Value.ToString());

            Reader.GlobalRequestLibrary.RequestList.RemoveRequestListRow(removeRequest);

            FS_Request_DGV.DataSource = Reader.GlobalRequestLibrary.RequestList;
            FS_Request_DGV.Refresh();

            _Indexer.SaveRequest();
        }

        private void rebuildAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Rebuild Library?. This will take some time to complete", "Rebuild Library", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                FileInfo delibfile = new FileInfo(Path.Combine(Settings.Default.LibraryDir, string.Format("{0}.{1}", Settings.Default.LibraryName, "xml")));
                delibfile.Delete();
                Reader.GlobalLibrary._Files.Clear();
                Initialize();
            }
        }

        #endregion Event Handlers

        private void openLibraryLocationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", string.Format("/select,{0}", Path.Combine(Settings.Default.LibraryDir, string.Format("{0}.{1}", Settings.Default.LibraryName, "fsl"))));
        }
    }
}